/**
 *
 */
package com.sanhai.android.service;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;

import com.sanhai.android.EduApplication;
import com.sanhai.android.util.PhoneInfo;
import com.sanhai.android.util.StringUtil;
import com.sanhai.android.util.Util;

import org.json.JSONObject;

import java.util.Map;

/**
 * @author mahuihuang
 */
public class Token {

    private final static String DEF_APPID = "sh01";

    private static final String TOKEN_KEY = "TOKEN_KEY_V2";

    protected long id = 0L;
    private static String netType = "";
    private static String userId = "";
    private static String terminal = "1";
    private static String deviceModel = "";
    private static String deviceId = "";
    private static String os = "";
    private static String tokenKey = "";

    private static String appId = "";
    private static String versionCode = "";
    private static Long updateTime = 0L;

    private static String xmppPwd = null;//XMPP连接密码

    private static String mainUserId = "";
    private static String mainUserName = "";
    // {
    // IP，PC访问时ip地址；移动终端访问时传网络类型（0:2G；1:3G；3:WIFI；4:其他网络）
    // UserId，（由服务器返回）
    // 终端类型，0：PC 0：1+移动终端APP版本
    // 终端设备型号，PC访问时置空，移动终端传设备型号
    // 终端标识，终端的唯一编号，PC访问时置空，移动终端传MEID或MAC或生成的UUID
    // OS，系统版本,
    // TOKEN数据（由服务器返回）
    // }
    private static String createTime = "";//
    private static String strongPoint = "";//
    private static String phone = "";//
    private static String schoolName = "";//
    private static String trueName = "";//
    private static String schooliden = "";//
    private static String weakAtCourse = "";//
    private static String department = "";//
    private static String introduce = "";//
    private static String type = "";//
    private static String trainingSchoolID = "";//
    private static String country = "";//
    private static String city = "";//
    private static String provience = "";//
    private static String honours = "";//
    private static String parentsName = "";//
    private static String email = "";//
    private static String manifesto = "";//
    private static String schoolID = "";//
    private static String faceUrl = "";
    private static Integer identity = null;//0：表示学生，1：表示老师, 2:家长
    private static Context context = null;

    private final static String KEY_TOKENDATA = "KEY_TOKENDATA";
    private final static String KEY_USERIDENTITY_TOKENDATA = "KEY_USERIDENTITY_TOKENDATA";
    private final static String KEY_MAINUSERID_TOKENDATA = "KEY_MAINUSERID_TOKENDATA";
    private final static String KEY_MAINUSERNAME_TOKENDATA = "KEY_MAINUSERNAME_TOKENDATA";

    /**
     * 设置保存用户身份 0学生 1老师  3家长
     *
     * @param identity
     */
    public static void setUserIdentity(int identity) {
        Token.identity = identity;
        Editor edit = getContext().getSharedPreferences(KEY_USERIDENTITY_TOKENDATA, Context.MODE_PRIVATE).edit();
        edit.putInt(KEY_USERIDENTITY_TOKENDATA, identity);
        edit.commit();
    }

    public static int getUserIdentity() {
        if (Token.identity == null) {
            Token.identity = getContext().getSharedPreferences(KEY_USERIDENTITY_TOKENDATA, Context.MODE_PRIVATE).getInt(KEY_USERIDENTITY_TOKENDATA, -1);
        }
        return Token.identity;
    }

    public static String getMainUserId() {
        if (Token.getUserIdentity() == 3) {
            if (StringUtil.isEmpty(Token.mainUserId)) {
                Token.mainUserId = getContext().getSharedPreferences(KEY_MAINUSERID_TOKENDATA, Context.MODE_PRIVATE).getString(KEY_MAINUSERID_TOKENDATA, "");
            }
            return Token.mainUserId;
        } else {
            return getUserId();
        }

    }

    public static void setMainUserId(String mainUserId) {
        Token.mainUserId = mainUserId;
        Editor edit = getContext().getSharedPreferences(KEY_MAINUSERID_TOKENDATA, Context.MODE_PRIVATE).edit();
        edit.putString(KEY_MAINUSERID_TOKENDATA, mainUserId);
        edit.commit();
    }

    public static String getMainUserName() {
        if (Token.getUserIdentity() == 3) {
            if (StringUtil.isEmpty(Token.mainUserName)) {
                Token.mainUserName = getContext().getSharedPreferences(KEY_MAINUSERNAME_TOKENDATA, Context.MODE_PRIVATE).getString(KEY_MAINUSERNAME_TOKENDATA, "");
            }
            return Token.mainUserName;
        } else {
            return getTrueName();
        }

    }

    public static void setMainUserName(String mainUserName) {
        Token.mainUserName = mainUserName;
        Editor edit = getContext().getSharedPreferences(KEY_MAINUSERNAME_TOKENDATA, Context.MODE_PRIVATE).edit();
        edit.putString(KEY_MAINUSERNAME_TOKENDATA, mainUserName);
        edit.commit();
    }

    public static String getUserIdentityName() {
        //0：表示学生，1：表示老师, 2:家长
        switch (Token.getUserIdentity()) {
            case 0:
                return "学生";
            case 1:
                return "老师";
            case 3:
                return "家长";
            case 8:
                return "校长";
            default:
                return "未知";
        }
    }

    public static Context getContext() {
        if (Token.context != null) {
            return Token.context;
        }
        return EduApplication.getContext();
    }

    public static void setContext(Context cont) {
        if (Token.getContext() == null && cont != null) {
            Token.context = cont;
        }
    }

    public static void fill(Context cont, Map<String, Object> data) {

        if (Token.getContext() == null && cont != null) {
            Token.context = cont;
        }

        Token.userId = Util.toString(data.get("userID"));
        Token.xmppPwd = Util.toString(data.get("xmppPwd"));
        Token.createTime = Util.toString(data.get("createTime"));
        Token.strongPoint = Util.toString(data.get("strongPoint"));
        Token.phone = Util.toString(data.get("phone"));
        Token.schoolName = Util.toString(data.get("schoolName"));
        Token.schoolID = Util.toString(data.get("schoolID"));
        Token.trueName = Util.toString(data.get("trueName"));
        Token.department = Util.toString(data.get("department"));
        Token.type = Util.toString(data.get("type"));
        Token.email = Util.toString(data.get("email"));
        Token.parentsName = Util.toString(data.get("parentsName"));
        Token.faceUrl = Util.toString(data.get("headImgUrl"));
        if (data.containsKey("sessionToken")) {
            Token.tokenKey = Util.toString(data.get("sessionToken"));
        }

        if (Util.isEmpty(Token.deviceId)) {
            Token.deviceId = new PhoneInfo(getContext()).getPhoineSN();
        }
        if (Util.isEmpty(Token.deviceModel)) {
            Token.deviceModel = android.os.Build.MODEL;
        }
        if (Util.isEmpty(Token.os)) {
            Token.os = android.os.Build.VERSION.RELEASE;
        }

        // 保存用户的token信息
        save();
    }

    /**
     * 注销Token
     */
    public static void logout(Context context) {
        Token.userId = "";
        Token.xmppPwd = "";
        Token.createTime = "";
        Token.strongPoint = "";
        Token.phone = "";
        Token.schoolName = "";
        Token.schoolID = "";
        Token.trueName = "";
        Token.department = "";
        Token.type = "";
        Token.identity = null;
        Token.email = "";
        Token.parentsName = "";
        Token.tokenKey = "";
        Token.faceUrl = "";
        Token.identity = 0;
        Token.mainUserId = "";
        Token.mainUserName = "";
        // 保存用户的token信息
        // this.db.update(token);
        Token.setMainUserId("");
        Token.setMainUserName("");

        Token.save();
    }

    /**
     * 登录是否有效
     *
     * @return
     */
    public static boolean tokenValid(Context cont) {
        if (Token.getContext() == null && cont != null) {
            Token.context = cont;
        }
        return !Util.isEmpty(getTokenKey()) && getUserIdentity() != -1;
    }

    public static String getTokenJson() {
        JSONObject json = new JSONObject();
        try {
            json.put("ip", Token.getNetType());
            json.put("uid", Token.getUserId());
            json.put("tm", Token.getTerminal());
            json.put("dm", Token.getDeviceModel());
            json.put("did", Token.getDeviceId());
            json.put("os", Token.getOs());
            json.put("token", Token.getTokenKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    private static void save() {
        Editor edit = getContext().getSharedPreferences(KEY_TOKENDATA, Context.MODE_PRIVATE).edit();
        edit.putString("userId", Token.userId);
        edit.putString("xmppPwd", Token.xmppPwd);
        edit.putString("createTime", Token.createTime);
        edit.putString("strongPoint", Token.strongPoint);
        edit.putString("phone", Token.phone);
        edit.putString("schoolName", Token.schoolName);
        edit.putString("schoolID", Token.schoolID);
        edit.putString("trueName", Token.trueName);
        edit.putString("department", Token.department);
        edit.putString("type", Token.type);
        edit.putString("email", Token.email);
        edit.putString("parentsName", Token.parentsName);
        edit.putString(TOKEN_KEY, Token.tokenKey);
        edit.putString("faceUrl", Token.faceUrl);

        edit.putString("deviceId", Token.deviceId);
        edit.putString("deviceModel", Token.deviceModel);
        edit.putString("os", Token.os);

        edit.commit();
    }

    private static void load() {
        if (getContext() == null) {
            return;
        }
        SharedPreferences sp = getContext().getSharedPreferences(KEY_TOKENDATA, Context.MODE_PRIVATE);
        if (Util.isEmpty(Token.userId)) {
            Token.userId = sp.getString("userId", "");
        }
        if (Util.isEmpty(Token.xmppPwd)) {
            Token.xmppPwd = sp.getString("xmppPwd", "");
        }

        if (Util.isEmpty(Token.createTime)) {
            Token.createTime = sp.getString("createTime", "");
        }
        if (Util.isEmpty(Token.strongPoint)) {
            Token.strongPoint = sp.getString("strongPoint", "");
        }
        if (Util.isEmpty(Token.phone)) {
            Token.phone = sp.getString("phone", "");
        }
        if (Util.isEmpty(Token.schoolName)) {
            Token.schoolName = sp.getString("schoolName", "");
        }
        if (Util.isEmpty(Token.schoolID)) {
            Token.schoolID = sp.getString("schoolID", "");
        }
        if (Util.isEmpty(Token.trueName)) {
            Token.trueName = sp.getString("trueName", "");
        }
        if (Util.isEmpty(Token.department)) {
            Token.department = sp.getString("department", "");
        }
        if (Util.isEmpty(Token.userId)) {
            Token.userId = sp.getString("type", "");
        }
        if (Util.isEmpty(Token.email)) {
            Token.email = sp.getString("email", "");
        }
        if (Util.isEmpty(Token.parentsName)) {
            Token.parentsName = sp.getString("parentsName", "");
        }
        if (Util.isEmpty(Token.tokenKey)) {
            Token.tokenKey = sp.getString(TOKEN_KEY, "");
        }
        if (Util.isEmpty(Token.faceUrl)) {
            Token.faceUrl = sp.getString("faceUrl", "");
        }

        if (Util.isEmpty(Token.deviceId)) {
            Token.deviceId = new PhoneInfo(getContext()).getPhoineSN();
        }
        if (Util.isEmpty(Token.deviceModel)) {
            Token.deviceModel = android.os.Build.MODEL;
        }
        if (Util.isEmpty(Token.os)) {
            Token.os = android.os.Build.VERSION.RELEASE;
        }
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public static String getNetType() {
        if (Util.isEmpty(Token.netType)) {
            load();
        }
        return netType;
    }

    public void setNetType(String netType) {
        Token.netType = netType;
    }

    public static String getUserId() {
        if (Util.isEmpty(Token.userId)) {
            load();
        }
        return userId;
    }

    public void setUserId(String userId) {
        Token.userId = userId;
    }

    public static String getTerminal() {
        if (Util.isEmpty(Token.terminal)) {
            load();
        }
        return terminal;
    }

    public void setTerminal(String terminal) {
        Token.terminal = terminal;
    }

    public static String getDeviceModel() {
        if (Util.isEmpty(Token.deviceModel)) {
            load();
        }
        return deviceModel;
    }

    public void setDeviceModel(String deviceModel) {
        Token.deviceModel = deviceModel;
    }

    public static String getDeviceId() {
        if (Util.isEmpty(Token.deviceId)) {
            load();
        }
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        Token.deviceId = deviceId;
    }

    public static String getOs() {
        if (Util.isEmpty(Token.os)) {
            load();
        }
        return os;
    }

    public void setOs(String os) {
        Token.os = os;
    }

    public static String getTokenKey() {
        if (Util.isEmpty(Token.tokenKey)) {
            load();
        }
        return tokenKey;
    }

    public void setTokenKey(String tokenKey) {
        Token.tokenKey = tokenKey;
    }

    public static Long getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Long updateTime) {
        Token.updateTime = updateTime;
    }

    public static String getCreateTime() {
        if (Util.isEmpty(Token.createTime)) {
            load();
        }
        return createTime;
    }

    public void setCreateTime(String createTime) {
        Token.createTime = createTime;
    }

    public static String getStrongPoint() {
        if (Util.isEmpty(Token.strongPoint)) {
            load();
        }
        return strongPoint;
    }

    public void setStrongPoint(String strongPoint) {
        Token.strongPoint = strongPoint;
    }

    public static String getPhone() {
        if (Util.isEmpty(Token.phone)) {
            load();
        }
        return phone;
    }

    public void setPhone(String phone) {
        Token.phone = phone;
    }

    public static String getSchoolName() {
        if (Util.isEmpty(Token.schoolName)) {
            load();
        }
        return schoolName;
    }

    public void setSchoolName(String schoolName) {
        Token.schoolName = schoolName;
    }

    public static String getTrueName() {
        if (Util.isEmpty(Token.trueName)) {
            load();
        }
        return trueName;
    }

    public void setTrueName(String trueName) {
        Token.trueName = trueName;
    }

    public static String getSchooliden() {
        if (Util.isEmpty(Token.schooliden)) {
            load();
        }
        return schooliden;
    }

    public void setSchooliden(String schooliden) {
        Token.schooliden = schooliden;
    }

    public static String getWeakAtCourse() {
        if (Util.isEmpty(Token.weakAtCourse)) {
            load();
        }
        return weakAtCourse;
    }

    public void setWeakAtCourse(String weakAtCourse) {
        Token.weakAtCourse = weakAtCourse;
    }

    public static String getDepartment() {
        if (Util.isEmpty(Token.department)) {
            load();
        }
        return department;
    }

    public void setDepartment(String department) {
        Token.department = department;
    }

    public static String getIntroduce() {
        if (Util.isEmpty(Token.introduce)) {
            load();
        }
        return introduce;
    }

    public void setIntroduce(String introduce) {
        Token.introduce = introduce;
    }

    public static String getType() {
        if (Util.isEmpty(Token.type)) {
            load();
        }
        return type;
    }

    public void setType(String type) {
        Token.type = type;
    }

    public static String getTrainingSchoolID() {
        if (Util.isEmpty(Token.trainingSchoolID)) {
            load();
        }
        return trainingSchoolID;
    }

    public void setTrainingSchoolID(String trainingSchoolID) {
        Token.trainingSchoolID = trainingSchoolID;
    }

    public static String getCountry() {
        if (Util.isEmpty(Token.country)) {
            load();
        }
        return country;
    }

    public void setCountry(String country) {
        Token.country = country;
    }

    public static String getCity() {
        if (Util.isEmpty(Token.city)) {
            load();
        }
        return city;
    }

    public void setCity(String city) {
        Token.city = city;
    }

    public static String getProvience() {
        if (Util.isEmpty(Token.provience)) {
            load();
        }
        return provience;
    }

    public void setProvience(String provience) {
        Token.provience = provience;
    }

    public static String getHonours() {
        if (Util.isEmpty(Token.honours)) {
            load();
        }
        return honours;
    }

    public void setHonours(String honours) {
        Token.honours = honours;
    }

    public static String getParentsName() {
        if (Util.isEmpty(Token.parentsName)) {
            load();
        }
        return parentsName;
    }

    public void setParentsName(String parentsName) {
        Token.parentsName = parentsName;
    }

    public static String getEmail() {
        if (Util.isEmpty(Token.email)) {
            load();
        }
        return email;
    }

    public void setEmail(String email) {
        Token.email = email;
    }

    public static String getManifesto() {
        if (Util.isEmpty(Token.manifesto)) {
            load();
        }
        return manifesto;
    }

    public void setManifesto(String manifesto) {
        Token.manifesto = manifesto;
    }

    public static String getSchoolID() {
        if (Util.isEmpty(Token.schoolID)) {
            load();
        }
        return schoolID;
    }

    public void setSchoolID(String schoolID) {
        Token.schoolID = schoolID;
    }

    public static String getFaceUrl() {
        if (Util.isEmpty(Token.faceUrl)) {
            load();
        }
        return faceUrl;
    }

    public static void setFaceUrl(String faceUrl) {
        Token.faceUrl = faceUrl;
        save();
    }

    public static String getXmppPwd() {
        if (Util.isEmpty(Token.xmppPwd)) {
            load();
        }
        return xmppPwd;
    }

    public static String getAppId() {
        if (Util.isEmpty(Token.appId)) {
            try {
                Token.appId = Token.getContext().getPackageManager().getApplicationInfo(Token.getContext().getPackageName(), PackageManager.GET_META_DATA).metaData.getString("appId");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (Util.isEmpty(Token.appId)) {
            return DEF_APPID;
        }
        return Token.appId;
    }

    public static String getVersionCode() {
        if (Util.isEmpty(Token.versionCode)) {
            try {
                Token.versionCode = Token.getContext().getPackageManager().getPackageInfo(Token.getContext().getPackageName(), 0).versionCode + "";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (Util.isEmpty(Token.versionCode)) {
            Token.versionCode = "1";
        }
        return Token.versionCode;
    }
}
